import Vue from 'vue'
import Vuex from 'vuex'
import {getItem, removeItem, removeToken, setItem} from "@/utils/auth";

import router from "@/router";
import {encrypt} from "@/utils/AES";
import {getUserInfo, loginApi, regApi} from "@/api/apiFox";
import {getCookie, setCookie} from "@/utils/Cookie";

Vue.use(Vuex)
const userKey = 'user'
const tokenKey = 'admin'

export default new Vuex.Store({
  state: {
    token: getCookie('token'),
    User: getItem('BaseUser') || ''
  },
  getters: {},
  mutations: {
    // 更新token
    saveToken(state, data) {
      state.token = data
      setCookie('token',data)
    },
    remove(state, data) {
      state.token = ''
      state.User = ''
      removeToken('token')
      router.push('/login').catch(err=>{})
    },

    // 更新用户信息
    updateUser(state, data) {
      setItem('user',data)
      state.User = data
      // state.User = encrypt(JSON.stringify(data))
      // setItem('BaseUser', encrypt(JSON.stringify(data)))
    },
  },
  actions: {
    loginSetToken({commit}, params) {
      return new Promise((resolve, reject) => {
        loginApi(params).then(res => {
          commit('saveToken', res)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },

    getUserList({commit}, params) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(res => {
          commit('updateUser', res)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      }).catch(err => {
      })
    },


    registertSet({commit},params){
      return new Promise((resolve,reject)=>{
        regApi(params).then(res=>{
          commit('saveToken', res)
          resolve(res.data)
        }).catch(err=>{
          reject(err)
        })
      })
    },

    removeLoginStatus({commit}, data) {
      // leaveLogin().then(res=>{}).catch(err=>{})
      // closeSocketWs()
      commit('remove', '')

    }

  },
  modules: {}
})
